package com.kgc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgc.bean.*;
import com.kgc.config.annotation.RequestPermission;
import com.kgc.config.annotation.RequestUser;
import com.kgc.form.GoogsItemFrom;
import com.kgc.service.OrderService;
import com.kgc.util.HttpUtils;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@Slf4j
@RequestMapping("/order")
@Api(tags = "订单信息操作入口")
public class OrderController {
    @Autowired(required = false)
    private OrderService orderService;

    //查询用户所有订单信息
    @RequestPermission
    @GetMapping("/myOrders")
    @ApiOperation(value = "查询所有订单信息，可根据订单状态查询", notes = "带订单状态识别码则查询该状态订单信息，如果不带则查询所有订单信息")
    public ReturnResult<List<OrderInfo>> myOrders(@ApiIgnore @RequestUser User user,
                                                  @ApiParam(name = "orderStateCode", value = "订单状态识别码") @RequestParam(required = false) Integer orderStateCode) {
        if (ObjectUtils.isEmpty(user)) {
            return ResultBuildUtil.fail("0900", "用户id为空！");
        } else if (null == orderStateCode) {
            //订单状态识别码为空，查询所有订单信息
            List<OrderInfo> data1 = orderService.queryAllOrders(user.getUserId());
            return ResultBuildUtil.success(data1);
        } else {
            //订单状态识别码不为空，查询该状态订单
            List<OrderInfo> data2 = orderService.queryAllOrdersByOrderState(user.getUserId(), orderStateCode);
            return ResultBuildUtil.success(data2);
        }


    }


    //根据订单编号查询订单信息
    @GetMapping("/orderInfo")
    @ApiOperation(value = "根据订单编号查询订单详情", notes = "传入订单编号，返回订单详情json")
    public ReturnResult<OrderInfo> orderInfo(@ApiParam(required = true, name = "orderId", value = "订单编号") @RequestParam String orderId) {
        if (null == orderService.queryOrderInfoByOrderId(orderId)) {
            //如果订单编号为空或失败则返回查询失败
            return ResultBuildUtil.fail("0901", "订单编号不存在或错误！");
        } else {
            //如果订单编号存在则返回订单详情
            OrderInfo data = orderService.queryOrderInfoByOrderId(orderId);
            return ResultBuildUtil.success(data);
        }
    }

    /**
     * @ClassName: OrderController
     * @Description 购物车下单
     * @Author lzy
     * @Date 2021/6/24
     */
    @RequestPermission
    @PostMapping("/orderGoods")
    @ApiOperation(value = "生成订单入口", notes = "地址先使用，用户默认的地址，")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adressId", value = "地址id"),
            @ApiImplicitParam(name = "orderPostFee", value = "邮费"),
            @ApiImplicitParam(name = "buyerMessage", value = "买家留言", required = false),
            @ApiImplicitParam(name = "discountId", value = "优惠卷编号", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 4044, message = "token无效"),
            @ApiResponse(code = 9655, message = "用户没有该优惠卷"),
            @ApiResponse(code = 9654, message = "用户优惠已使用，或者已过期"),
            @ApiResponse(code = 0000, message = "下单成功")

    })
    public ReturnResult<OrderInfoVo> userOrderGoodsItem(@ApiIgnore @RequestUser User user,
                                                        @RequestParam Integer adressId,
                                                        @RequestParam Integer orderPostFee,
                                                        @RequestParam(required = false) String buyerMessage,
                                                        @RequestParam(required = false) Integer discountId,
                                                        @RequestBody GoogsItemFrom... googsItemFroms
    ) {
        log.info("------生成订单信息: begin------");
        if (user == null || user.getUserId() == null) {
            return ResultBuildUtil.fail("4044", "token无效");
        }

        // 生成一个订单编号
        String tradeOrderNo = "T" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + UUID.randomUUID().toString().replace("-", "").substring(0, 6);

        // 计算总价格
        Integer totalMoney = 0;

        // 保存详细订单信息
        List<OrderItem> orderItems = new ArrayList<>();
        for (int i = 0; i < googsItemFroms.length; i++) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(tradeOrderNo);
            orderItem.setGoodsId(googsItemFroms[i].getGoodsId());
            orderItem.setNum(googsItemFroms[i].getNum());
            orderItem.setTitle(googsItemFroms[i].getTitle());
            orderItem.setPrePrice(googsItemFroms[i].getPrePrice());
            orderItem.setTotalPrice(googsItemFroms[i].getNum() * googsItemFroms[i].getPrePrice());
            orderItem.setPicPath(googsItemFroms[i].getPicPath());
            log.info(" -------- 保存订单{},商品{},详情成功！", tradeOrderNo, googsItemFroms[i].getGoodsId());
            orderItems.add(orderItem);
            totalMoney += orderItem.getTotalPrice();
        }

        // 保存商品详情到数据库
        orderService.querySaveOrderGoodsItem(orderItems);

        // 订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderPayment(totalMoney);


        // 会员打折金额
        Integer discountVipMoney = 0;
        // 判断用户是否是会员
        if (user.getIsvip() == 1) {
            // 会员打折后金额
            Integer totalMoney2 = new Double(totalMoney * 0.8).intValue();
            discountVipMoney = totalMoney - totalMoney2;
            orderInfo.setDiscountVipDicount(Byte.valueOf(discountVipMoney.toString()));
        }

        // 判断用户优惠卷是否可以使用
        if (orderService.justyUserHaveDiscountTick(user.getUserId(), discountId)) {
            return ResultBuildUtil.fail("9655", "用户没有该优惠卷");
        }
        // 判断用的优惠卷有没有使用过或失效
        if (orderService.justyUserUsedDiscountTick(user.getUserId(), discountId)) {
            return ResultBuildUtil.fail("9654", "用户优惠已使用，或者已过期");
        }
        // 优惠卷的金额
        Integer discountNewMoney = 0;

        if (null != discountId) {
            orderInfo.setDiscountTrckId(discountId);
            // 通过优惠卷id查询打折金额
            discountNewMoney = orderService.selectDiscountTrickById(discountId).getMoney();
            // 保存优惠卷金额
            orderInfo.setDiscountTrickMoney(discountNewMoney);
        }
        // 优惠的金额
        Integer finalDicountMoney = discountNewMoney + discountVipMoney;
        orderInfo.setDiscountAll(finalDicountMoney);
        // 最终的金额
        Integer finalTotalMoney = totalMoney - discountNewMoney - discountVipMoney;
        orderInfo.setLastPaymentPrice(finalTotalMoney);

        // 获得地址详情，并转换为JSON字符窜（放入用户默认下单地址）
        UserReviverInfo userReviverInfo = orderService.queryGetUserReviverInfoById(adressId);
        String userAdressInfo = JSON.toJSONString(userReviverInfo);
        orderInfo.setOrderLogisticsInfo(userAdressInfo);

        // 保存订单id
        orderInfo.setOrderId(tradeOrderNo);

        // 给默认的支付方式
        orderInfo.setOrderPaymentType(2);

        // 保存邮费
        orderInfo.setOrderPostFee(orderPostFee);

        // 保存时间
        orderInfo.setOrderCreateTime(new Date());

        // 保存用户id
        orderInfo.setUserId(user.getUserId());

        // 保存买家留言
        if (null != buyerMessage) {
            orderInfo.setBuyerMessage(buyerMessage);
        }
        // 异步保存订单信息
        orderService.querySaveOrderGoodsInfo(orderInfo);

        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setOrderId(tradeOrderNo);
        orderInfoVo.setOrderPayment(orderInfo.getLastPaymentPrice());

        return ResultBuildUtil.success(orderInfoVo);


    }


    @RequestPermission
    @ApiOperation(value = "调用第三方物流接口查询物流信息")
    @GetMapping("/queryLogistics")
    public ReturnResult<JSONObject> query(@ApiIgnore @RequestUser User user, @ApiParam(required = true, name = "orderId", value = "订单编号") @RequestParam String orderId) {
        if (ObjectUtils.isEmpty(user)) {
            return ResultBuildUtil.fail("0900", "用户id为空！");
        }
        if (null == orderService.queryOrderInfoByOrderId(orderId)) {
            //如果订单编号为空或失败则返回查询失败
            return ResultBuildUtil.fail("0901", "订单编号不存在或错误！");
        }
        //如果订单状态码为1或2，则返回未发货
        if (1 == orderService.queryOrderInfoByOrderId(orderId).getOrderStatus() || 2 == orderService.queryOrderInfoByOrderId(orderId).getOrderStatus()) {
            return ResultBuildUtil.fail("0918", "该订单尚未发货");
        }
        //如果查询非该用户的订单则返回订单非该用户
        if (!orderService.queryOrderInfoByOrderId(orderId).getUserId().equals(user.getUserId())) {
            return ResultBuildUtil.fail("0920", "此订单并非该用户的！");
        }
        //请求地址拼接
        String host = "https://ali-deliver.showapi.com";

        String path = "/showapi_expInfo";
        String method = "GET";
        String appcode = "a8ffa2946c344fae980a4a9c511d8564";
        //TODO 阿里云appcode
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        //放入物流公司名称
        querys.put("com", orderService.queryOrderInfoByOrderId(orderId).getOrderLogisticsName());
        //放入物流单号
        querys.put("nu", orderService.queryOrderInfoByOrderId(orderId).getOrderLogisticsCode());
        querys.put("receiverPhone", "receiverPhone");
        querys.put("senderPhone", "senderPhone");


        try {

            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultBuildUtil.success(getJsonObject(host, path, method, headers, querys));
        //统一返回类，成功，返回物流信息json对象
    }

    //getJsonObject方法将httpresponese转换为json对象
    private JSONObject getJsonObject(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) {
        HttpResponse response;
        String str = null;
        try {
            response = HttpUtils.doGet(host, path, method, headers, querys);
            str = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject;
    }


    /**
     * @ClassName: OrderController
     * @Description 商户发货
     * @Author lzy
     * @Date 2021/6/30
     */
    @PutMapping("/sendOrder")
    @ApiOperation(value = "商家发货", notes = "根据订单编号进行发货")
    @ApiResponses({
            @ApiResponse(code = 9001, message = "订单编号不存在或错误"),
            @ApiResponse(code = 9002, message = "发货失败"),
            @ApiResponse(code = 0000, message = "发货成功")
    })
    public ReturnResult<String> myOrders(@ApiParam(name = "orderId", value = "订单编号") @RequestParam String orderId) {

        // 判断该订单是否存在
        if (null == orderService.queryOrderInfoByOrderId(orderId)) {
            //如果订单编号为空或失败则返回查询失败
            return ResultBuildUtil.fail("9001", "订单编号不存在或错误！");
        }
        if (3 == orderService.queryOrderInfoByOrderId(orderId).getOrderStatus() || 1 == orderService.queryOrderInfoByOrderId(orderId).getOrderStatus()) {
            return ResultBuildUtil.fail("9003", "订单还未支付，或已发货");
        }

        OrderInfo orderInfo = orderService.queryOrderInfoByOrderId(orderId);

        orderInfo.setOrderStatus(3);
        orderInfo.setOrderLogisticsCode("YT5600799744323");
        orderInfo.setOrderLogisticsName("yuantong");

        // 更新订单状态
        if (orderService.queryUpdateOrderInfoByLoggistics(orderInfo)) {
            return ResultBuildUtil.success("发货成功");
        }
        return ResultBuildUtil.fail("9002", "发货失败");

    }


}
